import { ref, type Ref } from 'vue'

type SetStateAction<T> = T | ((prevState: T) => T)
type Dispatch<A> = (value: A) => void

export const useState = <T>(initialState: T): [Ref<T>, Dispatch<SetStateAction<T>>] => {
  const state = ref(initialState) as Ref<T>

  const setState = (newState: SetStateAction<T>) => {
    if (typeof newState === 'function') {
      state.value = (newState as (prevState: T) => T)(state.value)
    } else {
      state.value = newState
    }
  }

  return [state, setState]
}

